package com.bingxu.flink.advancedcode;

import com.bingxu.flink.bean.WaterSensor;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.triggers.Trigger;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.api.windowing.windows.Window;
import org.apache.flink.util.Collector;

import java.util.Collection;

/**
 * @author :BingXu
 * @description :TODO
 * @date :2021/8/16 9:35
 * @modifier :
 */

public class TumblingWind {
    public static void main(String[] args) throws Exception {
        // env
        Configuration conf = new Configuration();
        conf.setInteger("port", 19999);//指定env运行的端口
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);
        streamSource
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] fields = value.split(",");
                        return new WaterSensor(fields[0], Long.valueOf(fields[1]), Integer.valueOf(fields[2]));
                    }
                })
                .keyBy(ele -> ele.getId())
                // 时间窗口大小：5S
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String s,
                                        Context context,
                                        Iterable<WaterSensor> elements,
                                        Collector<String> out) throws Exception {
                        Long cnt=0l;
                        for (WaterSensor element : elements) {
                            if (element.getVc()>0) {
                                cnt++;
                            }
                        }
                        out.collect(context.window().getStart()+"分组内数据"+cnt+" "+context.window().getEnd());

                    }
                })
                .print();
        env.execute();

    }
}
